package com.kgc.controller;

import com.kgc.entity.Role;
import com.kgc.entity.UserInfo;
import com.kgc.entity.vo.UserInfoVo;
import com.kgc.service.RoleService;
import com.kgc.service.UserInfoService;
import com.kgc.utils.ConfigUtills;
import com.kgc.utils.JsonUtils;
import com.kgc.utils.ResultMapUtils;
import com.kgc.utils.TableResultMapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller //
@CrossOrigin //解决跨域
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    @ResponseBody
    public ResultMapUtils login(String userName, String userPwd,String pusername,boolean isShow, HttpSession session) {

        System.err.println("父级账号："+pusername);
        System.err.println("是否子账号："+isShow);

        //登录的实现
        if (userName == null || userName.equals("") || userPwd == null || userPwd.equals("")) {
            return ResultMapUtils.ERROR("-1", "用户名和密码不能为空");
        }

        UserInfo userInfo = userInfoService.getUserInfoByUserNameAndUserPwd(userName, userPwd,pusername,isShow);
        if (userInfo == null) {
            return ResultMapUtils.ERROR("-2", "用户名或密码错误");
        } else {
            //登录成功之后，把用户信息存放到session中
            session.setAttribute(ConfigUtills.SESSION_USER, userInfo);
            return ResultMapUtils.SUCCESS("登录成功");
        }
    }

    @RequestMapping("/shifouzhuce")
    @ResponseBody
    public ResultMapUtils coutUserInfo(String userName) {
        if (userName == null || userName.equals("")) {
            return ResultMapUtils.ERROR("-3", "用户名不能为空");
        }
        int i = userInfoService.countUserInfoByUserName(userName);
        if (i > 0) {
            return ResultMapUtils.ERROR("-4", "此用户已被注册，请换一个！");
        } else {
            return ResultMapUtils.SUCCESS("此用户名可以使用！");
        }
    }

    @RequestMapping("/goHomePage")
    public String goHomePage() {
        return "home";
    }

    @RequestMapping("/welcome")
    public String welcomePage() {
        return "welcome";
    }


    @RequestMapping("/user_list")
    public String userListPage(Model model) {
        List<Role> roles = roleService.getRoleList(1);
        model.addAttribute("roleList", roles);
        return "user_list";
    }


    /**
     * 用户列表分页实现
     *
     * @param limit 每页显示条数
     * @param page  当前页
     * @return
     */
    @RequestMapping("/user_all")
    @ResponseBody
    public ResultMapUtils getUserList(Integer limit, Integer page, String searchParams) {
        Map<String, Object> map = new HashMap<>();
        if (searchParams != null && !searchParams.equals("")) {
            map = JsonUtils.jsonToPojo(searchParams, Map.class);
        }

        //分页算法  需要知道 limit 两个参数是什么  limit index pageSize
        /**
         * 需要知道总记录数是多少
         */

        int count = userInfoService.countUserInfoAll(map);//总记录数
        //当前页-1 * 每页显示条数 = pageIndex
        int index = (page - 1) * limit;

        List<UserInfoVo> userInfoAll = userInfoService.getUserInfoAll(index, limit, map);

        return TableResultMapUtils.SUCCESS(userInfoAll, count);
    }

    @RequestMapping("/child_list")
    public String childListPage(Model model) {
        List<Role> roles = roleService.getRoleList(1);
        model.addAttribute("roleList", roles);
        return "child_list";
    }

    /**
     * 商户账号 看看当前子账号列表
     * @param limit 每页显示条数
     * @param page 当前页
     * @param searchParams 搜索条件
     * @param session session作用域 用户取出当前登录用户信息
     * @return
     */
    @RequestMapping("/sub_user_all")
    @ResponseBody
    public ResultMapUtils getSubUserList(Integer limit, Integer page, String searchParams,HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        if (searchParams != null && !searchParams.equals("")) {
            map = JsonUtils.jsonToPojo(searchParams, Map.class);
        }

        UserInfo userInfo = (UserInfo)session.getAttribute(ConfigUtills.SESSION_USER);
        map.put("pId",userInfo.getId());
        //分页算法  需要知道 limit 两个参数是什么  limit index pageSize
        /**
         * 需要知道总记录数是多少
         */
        int count = userInfoService.countUserInfoAll(map);//总记录数
        //当前页-1 * 每页显示条数 = pageIndex
        int index = (page - 1) * limit;

        List<UserInfoVo> userInfoAll = userInfoService.getUserInfoAll(index, limit, map);

        return TableResultMapUtils.SUCCESS(userInfoAll, count);
    }

    @RequestMapping("/add_user_page")
    public String addUserPage(Model model) {
        List<Role> roleList = roleService.getRoleList(1);
        model.addAttribute("roleList",roleList);
        return "add_user_page";
    }
    @RequestMapping("/add_child_page")
    public String addChildPage(Model model) {
        /*List<Role> roleList = roleService.getRoleList(1);
        model.addAttribute("roleList",roleList);*/
        return "add_child_page";
    }
    @RequestMapping("/update_child_page")
    public String updateUserPage(Integer id,Model model) {
        /*List<Role> roleList = roleService.getRoleList(1);
        model.addAttribute("roleList",roleList);*/
        //获取用户信息
        UserInfoVo userInfo=userInfoService.getUserInfoById(id);
        model.addAttribute("user",userInfo);
        //获取用户角色

        return "update_child_page";
    }

    @RequestMapping("/add_user")
    @ResponseBody
    public ResultMapUtils addUserInfo(UserInfo userInfo,Integer roleId,Integer type) {
        if (userInfo == null) {
            return ResultMapUtils.ERROR("-addUser-1", "参数异常");
        }

        int countUser=userInfoService.countUserInfoByUserName(userInfo.getUserName());

        if (countUser>0){
            return ResultMapUtils.ERROR("-adduser-3","此用户名已经存在，请换一个");
        }
        Integer num = userInfoService.addUserInfo(userInfo,type);
        if (roleId!=null&&roleId!=0){
            //添加角色操作
            roleService.addRoleUserInfo(roleId,userInfo.getId());
        }
        if (num > 0) {
            return ResultMapUtils.SUCCESS("新增成功");
        }

        return ResultMapUtils.ERROR("-addUser-2", "系统异常，新增失败");

    }
    @RequestMapping("/add_child")
    @ResponseBody
    public ResultMapUtils addUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            return ResultMapUtils.ERROR("-addUser-1", "参数异常");
        }

        int countUser=userInfoService.countUserInfoByUserName(userInfo.getUserName());

        if (countUser>0){
            return ResultMapUtils.ERROR("-adduser-3","此用户名已经存在，请换一个");
        }
        Integer num = userInfoService.addUserInfo(userInfo);
        /*
        if (roleId!=null&&roleId!=0){
            //添加角色操作
            roleService.addRoleUserInfo(roleId,userInfo.getId());
        }
       */
        if (num > 0) {
            return ResultMapUtils.SUCCESS("新增成功");
        }

        return ResultMapUtils.ERROR("-addUser-2", "系统异常，新增失败");

    }

    @RequestMapping("/update_child")
    @ResponseBody
    public ResultMapUtils saveUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            return ResultMapUtils.ERROR("-addUser-1", "参数异常");
        }

        Integer num = userInfoService.updateUserInfo(userInfo);
        /*if (roleId!=null&&roleId!=0){
            //修改角色操作
            roleService.updateUserRole(userInfo.getId(),roleId);
        }*/
        if (num > 0) {
            return ResultMapUtils.SUCCESS("新增成功");
        }

        return ResultMapUtils.ERROR("-addUser-2", "系统异常，新增失败");

    }

    @RequestMapping("/update_user")
    @ResponseBody
    public ResultMapUtils updateUserInfo(String field, String value, Integer id) {

        if (id == null) {
            return ResultMapUtils.ERROR("-upuser01", "参数异常");
        }
        int num = userInfoService.updateUserInfo(field, value, id);
        if (num > 0) {
            return ResultMapUtils.SUCCESS("修改成功");
        }
        return ResultMapUtils.ERROR("-upuser02", "系统异常，修改失败!");
    }


    @RequestMapping("/del_user")
    @ResponseBody
    public ResultMapUtils delUserInfo(Integer id) {
        if (id == null) {
            return ResultMapUtils.ERROR("-deluser-1", "参数异常");
        }

        int num = userInfoService.delUserInfoById(id);
        if (num > 0) {
            return ResultMapUtils.SUCCESS("删除成功");
        } else {
            return ResultMapUtils.ERROR("-deluser-2", "系统异常，删除失败");
        }
    }

    @RequestMapping("/update_user_role")
    public String updateUserRole(Model model,Integer id){
        Role role= roleService.getRoleInfoByUserId(id);
        if (role==null){
            role=new Role();
        }
        List<Role> roleList = roleService.getRoleList(1);
        model.addAttribute("roleList",roleList);
        model.addAttribute("userId",id);
        model.addAttribute("userRole",role);
        return "update_user_role";
    }


    @RequestMapping("/upUserRole")
    @ResponseBody
    public ResultMapUtils upUserRole(Integer id,Integer roleId){
        if (id==null||roleId==null){
            return ResultMapUtils.ERROR("-upur-1","参数异常");
        }

        int num=roleService.updateUserRole(id,roleId);
        if (num > 0) {
            return ResultMapUtils.SUCCESS("修改成功");
        } else {
            return ResultMapUtils.ERROR("-upur-2", "系统异常，修改失败");
        }
    }


    @RequestMapping("/sys_login")
    public String sysLoginPage(){
        return "login";
    }

    @RequestMapping("/sub_user_list")
    public String subUserListPage(){
        return "merchant/user_list";
    }

    @RequestMapping("/goChildAuth")
    public String goShouQuanPage(Integer userId,Model model){
        model.addAttribute("userId",userId);
        return "child_shouquan";
    }
    @RequestMapping("/update_userMenu")
    @ResponseBody
    public ResultMapUtils updateRoleMenu(String checkedIds,Integer userId){
        if (userId==null){
            return ResultMapUtils.ERROR("uprm-1","参数异常");
        }
//        int num=roleService.updateRoleMenu(checkedIds,roleId);
        int num=userInfoService.updateUserMenu(checkedIds,userId);
        if (num>0){
            return ResultMapUtils.SUCCESS("更新成功");
        }else {
            return ResultMapUtils.ERROR("uprm-2","更新失败");
        }
    }
}
